<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Client\Action\Dashboard;

use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\Client\Logic\IndexLogic;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 跟进时获取客户详情.
 * @Controller
 */
class Client extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     *
     * @RequestMapping(path="/dashboard/client/getInfo", methods="GET")
     */
    public function handle()
    {
        $user = user();
        if (empty($user)) {
            throw new CommonException(ErrorCode::AUTH_UNAUTHORIZED, '登入异常请重新登入');
        }
        $data = $this->request->all();
        $detail = Db::table('client as client')
            ->leftJoin('client_contact_pivot as pivot', 'pivot.client_id', '=', 'client.id')
            ->leftJoin('work_contact as contact', 'contact.id', '=', 'pivot.contact_id')
            ->when(isset($data['client_id']) && is_numeric($data['client_id']), function ($query) use ($data) {
                $query->where('client.id', $data['client_id']);
            })
            ->groupBy([
                'client.id'
            ])
            ->select([
                'client.enterprise_name',
                'client.id',
                Db::raw('GROUP_CONCAT(mc_contact.name ORDER BY mc_contact.id ASC SEPARATOR ",") AS contact_name'),
                'client.mobile',
                'client.level',
            ])->first();
        $record = Db::table('client_follow_record as record')
            ->join('work_employee as employee', 'employee.id', '=', 'record.user_id')
            ->where('record.client_id', $data['client_id'])
            ->orderBy('record.followed_at', 'desc')
            ->select([
                'employee.name',
                'record.followed_at',
                'record.type',
                'record.remark',
                'record.returned_at',
            ])
            ->first();
        $record || $record = [
            'name' => '',
            'followed_at' => '',
            'type' => '',
            'remark' => ''
        ];
        $record = collect($record)->toArray();
        $detail = collect($detail)->toArray();
        //类型（1：电话。2：面访。3：企业微信）
        $record['type_string'] = '';
        if ($record['type'] == 1) {
            $record['type_string'] = '电话';
        }
        if ($record['type'] == 2) {
            $record['type_string'] = '面访';
        }
        if ($record['type'] == 3) {
            $record['type_string'] = '企业微信';
        }
        return array_merge($detail, $record);
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'status' => 'integer',
            'page' => 'integer',
            'perPage' => 'integer',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'status.integer' => '成员状态必须为整数',
            'page.integer' => '页码必须为整数',
            'perPage.integer' => '页码必须为整数',
        ];
    }
}
